package com.vae.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vae.base.enums.CourseEnum;
import com.vae.base.enums.SystemExceptionEnum;
import com.vae.base.exception.SystemException;
import com.vae.base.utils.SecurityUtil;
import com.vae.content.config.MultipartSupportConfig;
import com.vae.content.domain.dto.CourseBaseInfoDto;
import com.vae.content.domain.dto.CoursePreviewDto;
import com.vae.content.domain.dto.TeachplanDto;
import com.vae.content.domain.entity.*;
import com.vae.content.feignclient.MediaServiceClient;
import com.vae.content.mapper.CourseBaseMapper;
import com.vae.content.mapper.CourseMarketMapper;
import com.vae.content.mapper.CoursePublishMapper;
import com.vae.content.mapper.CoursePublishPreMapper;
import com.vae.content.service.*;
import com.vae.domain.MqMessage;
import com.vae.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author: 35238
 * 功能: 课程预览
 * 时间: 2024-05-22 22:02
 */
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish>  implements CoursePublishService {

    @Autowired
    CourseBaseService courseBaseService;

    @Autowired
    TeachplanService teachplanService;

    @Autowired
    CourseTeacherService courseTeacherService;

    @Autowired
    CoursePublishService coursePublishService;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    CoursePublishMapper coursePublishMapper;

    @Autowired
    MediaServiceClient mediaServiceClient;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * @description 获取课程预览信息
     * @param courseId 课程id
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {

        //课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseService.getCourseBaseInfo(courseId);

        //课程计划信息
        List<TeachplanDto> teachplanTree= teachplanService.findTeachplanTree(courseId);

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }

    /**
     * 课程提交审核
     * @param companyId
     * @param courseId  课程id
     */
    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {

        //约束校验
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //课程审核状态
        String auditStatus = courseBase.getAuditStatus().getCode();
        //当前审核状态为已提交不允许再次提交
        if("202003".equals(auditStatus)){
            SystemException.cast("当前为等待审核状态，审核完成可以再次提交。");
        }
        //本机构只允许提交本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            SystemException.cast("不允许提交其它机构的课程。");
        }

        //课程图片是否填写
        if(StringUtils.isEmpty(courseBase.getPic())){
            SystemException.cast("提交失败，请上传课程图片");
        }

        //添加课程预发布记录
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //课程基本信息加部分营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseService.getCourseBaseInfo(courseId);
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转为json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        //将课程营销信息json数据放入课程预发布表
        coursePublishPre.setMarket(courseMarketJson);

        //查询课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if(teachplanTree.size()<=0){
            SystemException.cast("提交失败，还没有添加课程计划");
        }
        //转json
        String teachplanTreeString = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplanTreeString);

        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //课程id
        coursePublishPre.setId(courseId);
        //提交时间
        coursePublishPre.setCreateDate(new Date());

        //任课老师
        LambdaQueryWrapper<CourseTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> teacherList = courseTeacherService.list(wrapper);
        if (teacherList!=null) {
            coursePublishPre.setTeachers(JSON.toJSONString(teacherList));
        }

        //是否收费
        CoursePreviewDto coursePreviewInfo = coursePublishService.getCoursePreviewInfo(courseId);
        if(coursePreviewInfo.getCourseBase().getCharge()!=null) {
            coursePublishPre.setCharge(coursePreviewInfo.getCourseBase().getCharge().getCode());
        }

        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPreUpdate == null){
            //添加课程预发布记录
            coursePublishPreMapper.insert(coursePublishPre);
        }else{
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        //更新课程基本表的审核状态
        courseBase.setAuditStatus(CourseEnum.AUDIT_SUBMIT_YES);
        courseBaseMapper.updateById(courseBase);
    }


    /**
     * 课程发布
     * @param companyId 机构id
     * @param courseId 课程id
     */
    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {

        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre == null){
            SystemException.cast("请先提交课程审核，审核通过才可以发布");
        }
        //本机构只允许提交本机构的课程
        if(!coursePublishPre.getCompanyId().equals(companyId)){
            SystemException.cast("不允许提交其它机构的课程。");
        }

        //课程审核状态
        String auditStatus = coursePublishPre.getStatus();
        //审核通过方可发布
        if(!"202004".equals(auditStatus)){
            SystemException.cast("操作失败，课程审核通过方可发布。");
        }

        //保存课程发布信息
        saveCoursePublish(courseId);

        //保存消息表
        saveCoursePublishMessage(courseId);

        //删除课程预发布表对应记录
        coursePublishPreMapper.deleteById(courseId);

    }

    //保存课程发布信息
    private void saveCoursePublish(Long courseId){
        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre == null){
            SystemException.cast("课程预发布数据为空");
        }

        CoursePublish coursePublish = new CoursePublish();

        //拷贝到课程发布对象
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        coursePublish.setStatus(CourseEnum.PUBLISH_YES.getCode());
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if(coursePublishUpdate == null){
            coursePublishMapper.insert(coursePublish);
        }else{
            coursePublishMapper.updateById(coursePublish);
        }
        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus(CourseEnum.PUBLISH_YES);
        courseBaseMapper.updateById(courseBase);

    }

    //发送mq消息。保存消息表
    private void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if(mqMessage==null){
            SystemException.cast(SystemExceptionEnum.UNKOWN_ERROR);
        }
    }

    /**
     * 课程静态化
     * @param courseId  课程id
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {

        Configuration configuration = new Configuration(Configuration.getVersion());
        //最终的静态文件
        File htmlFile = null;
        try {
            //拿到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            //指定模板的目录
            configuration.setDirectoryForTemplateLoading(new File(classpath+"/templates/"));
            //指定编码
            configuration.setDefaultEncoding("utf-8");

            //得到模板
            Template template = configuration.getTemplate("course_template.html");
            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            //获取任课老师
            LambdaQueryWrapper<CourseTeacher> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseTeacher::getCourseId,courseId);
            List<CourseTeacher> teacherList = courseTeacherService.list(wrapper);
            if (teacherList!=null) {
                coursePreviewInfo.setTeachers(teacherList);
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("model",coursePreviewInfo);

            //Template template 模板, Object model 数据
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //输入流
            InputStream inputStream = IOUtils.toInputStream(html, "utf-8");
            htmlFile = File.createTempFile("coursepublish",".html");
            //输出文件
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            //使用流将html写入文件
            IOUtils.copy(inputStream,outputStream);
        }catch (Exception ex){
            System.err.println("页面静态化出现问题,课程id: "+courseId);
            ex.printStackTrace();
        }
        return htmlFile;
    }

    /**
     * 上传课程静态化页面
     * @param courseId
     * @param file  静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file,Long companyId) {
        try {

            //将file转成MultipartFile
            MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
            //远程调用得到返回值
            String upload = mediaServiceClient.uploadFile(multipartFile, "course/"+courseId+".html", companyId);
            if(upload==null){
                System.err.println("xue-content-service模块在远程调用xue-media-api模块时无响应或发生异常，已被熔断，课程id: "+courseId);
                SystemException.cast("上传静态文件过程中存在异常");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            SystemException.cast("上传静态文件过程中存在异常");
        }
    }


    /**
     * 获取课程发布信息
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursePublish(Long courseId){
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish ;
    }

    /**
     * 获取缓存里课程发布信息
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursePublishCache(Long courseId){

        //查询缓存
        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        if(jsonObj!=null){
            String jsonString = jsonObj.toString();
            //处理缓存穿透
            if(jsonString.equals("null"))
                return null;
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        } else {
            //锁的名字就是"lockexist:" + courseId，这个锁就是给redisson来操作的(锁的命名注意要加courseId来区分)，这个锁的过期时间默认是30秒
            //请确保你redisTemplate.opsForValue().set的不是这个锁，锁就是key的意思，不然同样的锁会报错
            RLock lockExist = redissonClient.getLock("lockexist:" + courseId);
            //获取分布式锁
            lockExist.lock();
            try {//只要执行try，就说明获取到锁
                Object jsonObjTemp = redisTemplate.opsForValue().get("course:" + courseId);
                if (jsonObjTemp != null) {
                    String jsonString = jsonObjTemp.toString();
                    CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
                    return coursePublish;
                }
                //从数据库查询
                CoursePublish coursePublish = getCoursePublish(courseId);
                //处理缓存雪崩。不需要设置过期时间: 300秒 + 0~99随机数。这个锁是存数据的，不是给redisson去操作的
                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish), 300+new Random().nextInt(100), TimeUnit.SECONDS);
                return coursePublish;
            } finally {
                //释放锁
                lockExist.unlock();
            }
        }
    }


}
